package com.example.controller.redis;

import com.example.component.common.RedisUtil;
import com.example.constant.redis.RedisKeyConstant;
import com.example.service.redis.TestService;
import com.example.pojo.vo.common.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.PostConstruct;
import java.util.List;
import java.util.Optional;

/**
 * @author LiYuhang
 * @version 0.1
 * @application cache TestController
 * CacheAside Pattern
 * 读 先读缓存 缓存没有 读数据库
 * 写 先写数据库 再删除缓存
 * @Date 2020/9/23 10:34
 */
@RestController
@RequestMapping("test")
@Slf4j(topic = "CACHE-TestController")
public class TestController {

    @Autowired
    RedisUtil redisUtil;

    @Autowired
    @Qualifier(value = "redisTemplate")
    RedisTemplate redisTemplate;

    @Autowired
    TestService testService;

    @PostConstruct
    public void init() {
        redisUtil.setRedisTemplate(redisTemplate);
    }

    @RequestMapping(value = "search")
    public Result search(){
        Optional<Object> data=Optional.ofNullable(redisUtil.get(RedisKeyConstant.REDEI_KEY));
        log.info("从redis中读取 data 是否有数据:{}",data.isPresent());
//        String string = null;
//        System.out.println(string.toString());
        if(data.isPresent()){
            return Result.OK((List<String>)data.get());
        }else{
            List<String> dataList=testService.getDataList();;
            redisUtil.set(RedisKeyConstant.REDEI_KEY,dataList);
            log.info("从数据库读取data size:{}",dataList.size());
            return Result.OK(testService.getDataList());
        }
    }
    @RequestMapping(value = "write")
    public Result write( ){
        //write to Database
        boolean flag=testService.writToDb();
        if(flag){
            redisUtil.del(RedisKeyConstant.REDEI_KEY);
            return Result.OK("数据更新成功");
        }else{
            return Result.error("数据修改失败");
        }
    }

}
